package com.itheima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.LoginDto;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import com.itheima.user.mapper.ApUserMapper;
import com.itheima.user.service.ApUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author mgw
 * @create 2021/9/24 20:12
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        //判断手机号密码是否为空
        if (!StringUtils.isEmpty(dto.getPhone()) && !StringUtils.isEmpty(dto.getPassword())) {
            //手机号加盐加密
            QueryWrapper<ApUser> queryWrapper = new QueryWrapper<ApUser>();
            queryWrapper.eq("phone", dto.getPhone());
            ApUser apUser = apUserMapper.selectOne(queryWrapper);
            if (null != apUser) {
                String salt = apUser.getSalt();
                String encodeWithSalt = MD5Utils.encodeWithSalt(dto.getPassword(), salt);
                //从数据库中取出密码进行比对
                if (apUser.getPassword().equals(encodeWithSalt)) {
                    //正确则生成token
                    String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
                    apUser.setPassword("*");
                    Map<String,Object> apUserHashMap = new HashMap<>();
                    apUserHashMap.put("token",token);
                    apUserHashMap.put("user",apUser);
                    return ResponseResult.okResult(apUserHashMap);
                }
            }
        }else {
            //如果是游客登录则生成令牌并表记为0
            String token = AppJwtUtil.getToken(0L);
            Map<String,Object> apUserHashMap = new HashMap<>();
            apUserHashMap.put("token",token);
            return ResponseResult.okResult(apUserHashMap);
        }
        //用户不存在或者错误返回错误码
        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,
                AppHttpCodeEnum.LOGIN_PASSWORD_ERROR.getErrorMessage());
    }
}
